package com.thundersoft.mm.phone;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;

import android.content.Intent;
import android.content.IntentFilter;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;


public class PhoneCall {
	private static TelephonyManager tm;
	private static Context context;
	private static boolean hasRing = false;
	private static PhoneStateListener listener=new PhoneStateListener(){
		@Override   
		public void onCallStateChanged(int state, String incomingNumber) {   
			super.onCallStateChanged(state, incomingNumber);   
			switch(state){   
				case TelephonyManager.CALL_STATE_IDLE: 
					if(TextUtils.isEmpty(incomingNumber)){
						hasRing = false;
						Log.i("arlauncher","电话空闲");
						ConnectionManager.sendPhoneIdel();
					}else{
						hasRing = false;
						ConnectionManager.sendPhoneReject();
						Log.i("arlauncher","电话挂断 "+incomingNumber);
					}
					break;   
				case TelephonyManager.CALL_STATE_OFFHOOK:
					if (!hasRing){
						Log.i("arlauncher","拨打 "+incomingNumber);
						ConnectionManager.sendPhoneOutCall(incomingNumber);
					}else{
						hasRing = false;
						Log.i("arlauncher","接听 "+incomingNumber);
						ConnectionManager.sendPhoneAccepted(incomingNumber);
					}
					break;
				case TelephonyManager.CALL_STATE_RINGING:
					hasRing  = true;
					ConnectionManager.sendPhoneRinging(incomingNumber);
					Log.i("arlauncher","响铃 "+incomingNumber);
					break;   
			}   
		}   
	};   

	public  static void init(Context c) {
		context = c;
		tm = (TelephonyManager)context.getSystemService(Service.TELEPHONY_SERVICE); 
		tm.listen(listener,PhoneStateListener.LISTEN_CALL_STATE);
	}
}
